import { api } from './request'

/**
 * 传感器数据相关API
 */

// 获取最新传感器数据
export const getLatestSensorData = () => {
  return api.get('/sensors/latest')
}

// 获取历史数据
export const getSensorData = (hours = 24) => {
  return api.get('/sensors/history', { hours })
}

// 获取历史数据（分页）
export const getSensorDataPaged = (hours = 24, page = 0, size = 100) => {
  return api.get('/sensors/history-paged', { hours, page, size })
}

// 获取指定时间范围的数据
export const getSensorDataByRange = (startTime, endTime) => {
  return api.get('/sensors/range', { startTime, endTime })
}

// 获取最近N天的数据
export const getRecentDaysData = (days = 7) => {
  return api.get('/sensors/recent-days', { days })
}

// 获取每小时平均数据
export const getHourlyAverageData = (hours = 24) => {
  return api.get('/sensors/hourly-average', { hours })
}

// 获取每小时数据（一天内的数据）
export const getHourlyData = (hours = 24) => {
  return api.get('/sensors/hourly-data', { hours })
}

// 获取每日统计数据
export const getDailyStatistics = (days = 7) => {
  return api.get('/sensors/daily-statistics', { days })
}

// 获取数据统计信息
export const getDataStatistics = () => {
  return api.get('/sensors/statistics')
}

// 获取最近10条数据
export const getLatest10Data = () => {
  return api.get('/sensors/latest-10')
}

// 添加传感器数据（用于测试）
export const addSensorData = (data) => {
  return api.post('/sensors/add', data)
}

// 批量添加传感器数据
export const batchAddSensorData = (dataList) => {
  return api.post('/sensors/batch-add', dataList)
}

// 导出数据
export const exportSensorData = (params) => {
  return api.download('/sensors/export', params)
}

// 实时数据流（WebSocket或SSE）
export const createRealtimeConnection = (callback) => {
  // 这里可以实现WebSocket连接
  // 目前使用轮询方式模拟实时数据
  const interval = setInterval(async () => {
    try {
      const response = await getLatestSensorData()
      if (response.success) {
        callback(response.data)
      }
    } catch (error) {
      console.error('获取实时数据失败:', error)
    }
  }, 3000) // 每3秒获取一次
  
  return () => clearInterval(interval)
}

// 数据验证
export const validateSensorData = (data) => {
  const errors = []
  
  if (!data.temperature || isNaN(data.temperature)) {
    errors.push('温度数据无效')
  } else if (data.temperature < -50 || data.temperature > 80) {
    errors.push('温度数据超出合理范围(-50°C ~ 80°C)')
  }
  
  if (!data.humidity || isNaN(data.humidity)) {
    errors.push('湿度数据无效')
  } else if (data.humidity < 0 || data.humidity > 100) {
    errors.push('湿度数据超出合理范围(0% ~ 100%)')
  }
  
  if (!data.pressure || isNaN(data.pressure)) {
    errors.push('气压数据无效')
  } else if (data.pressure < 80000 || data.pressure > 120000) {
    errors.push('气压数据超出合理范围(80000Pa ~ 120000Pa)')
  }
  
  if (!data.lightIntensity || isNaN(data.lightIntensity)) {
    errors.push('光照强度数据无效')
  } else if (data.lightIntensity < 0 || data.lightIntensity > 2000) {
    errors.push('光照强度数据超出合理范围(0 ~ 2000)')
  }
  
  return {
    isValid: errors.length === 0,
    errors
  }
}

// 数据格式化
export const formatSensorData = (data) => {
  if (!data) return null
  
  return {
    id: data.id,
    temperature: parseFloat(data.temperature).toFixed(1),
    humidity: parseFloat(data.humidity).toFixed(1),
    pressure: parseFloat(data.pressure).toFixed(0),
    lightIntensity: parseInt(data.lightIntensity),
    createdAt: data.createdAt,
    updatedAt: data.updatedAt
  }
}

// 数据单位转换
export const convertUnits = {
  // 温度转换
  celsiusToFahrenheit: (celsius) => (celsius * 9/5) + 32,
  fahrenheitToCelsius: (fahrenheit) => (fahrenheit - 32) * 5/9,
  
  // 气压转换
  paToHpa: (pa) => pa / 100,
  hpaToPa: (hpa) => hpa * 100,
  paToMmhg: (pa) => pa * 0.00750062,
  mmhgToPa: (mmhg) => mmhg / 0.00750062,
  
  // 光照强度转换
  luxToFootCandle: (lux) => lux * 0.092903,
  footCandleToLux: (fc) => fc / 0.092903
}

// 数据质量评估
export const assessDataQuality = (dataList) => {
  if (!dataList || dataList.length === 0) {
    return {
      quality: 'poor',
      score: 0,
      issues: ['无数据']
    }
  }
  
  const issues = []
  let score = 100
  
  // 检查数据完整性
  const missingDataCount = dataList.filter(item => 
    !item.temperature || !item.humidity || !item.pressure || !item.lightIntensity
  ).length
  
  if (missingDataCount > 0) {
    const missingRate = missingDataCount / dataList.length
    score -= missingRate * 30
    issues.push(`${(missingRate * 100).toFixed(1)}% 的数据不完整`)
  }
  
  // 检查数据异常值
  const outliers = dataList.filter(item => {
    return item.temperature < -20 || item.temperature > 60 ||
           item.humidity < 10 || item.humidity > 95 ||
           item.pressure < 90000 || item.pressure > 110000
  })
  
  if (outliers.length > 0) {
    const outlierRate = outliers.length / dataList.length
    score -= outlierRate * 20
    issues.push(`${(outlierRate * 100).toFixed(1)}% 的数据存在异常值`)
  }
  
  // 检查数据时间间隔
  if (dataList.length > 1) {
    const intervals = []
    for (let i = 1; i < dataList.length; i++) {
      const prev = new Date(dataList[i-1].createdAt)
      const curr = new Date(dataList[i].createdAt)
      intervals.push(Math.abs(curr - prev))
    }
    
    const avgInterval = intervals.reduce((a, b) => a + b, 0) / intervals.length
    const maxInterval = Math.max(...intervals)
    
    if (maxInterval > avgInterval * 3) {
      score -= 10
      issues.push('数据采集间隔不均匀')
    }
  }
  
  let quality = 'excellent'
  if (score < 60) quality = 'poor'
  else if (score < 80) quality = 'fair'
  else if (score < 90) quality = 'good'
  
  return {
    quality,
    score: Math.max(0, Math.round(score)),
    issues: issues.length > 0 ? issues : ['数据质量良好']
  }
}

// 获取每月统计数据
export const getMonthlyStatistics = (months = 12) => {
  return api.get('/sensors/monthly-statistics', { months })
}

// 获取自动聚合数据（根据时间范围自动选择聚合级别）
export const getAutoAggregatedData = (hours = 24) => {
  return api.get('/sensors/auto-aggregated', { hours })
}

// 测试数据库连接和数据
export const testDatabase = () => {
  return api.get('/sensors/test-db')
}